<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;

class CategoryController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('所有分类')
            ->row(function (Row $row) {
                $row->column(6, $this->tree());

                $row->column(6, function (Column $column) {
                    $form = new \Encore\Admin\Widgets\Form();
                    $form->action(url('admin/categories'));
                    $form->select('parent_id', '父级菜单')->options(Category::selectOptions());
                    $form->text('title', '标题')->rules('required');
                    $form->text('url', '链接');
                    $form->hidden('_token')->default(csrf_token());
                    $column->append((new Box(trans('admin.new'), $form))->style('success'));
                });
            });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑分类')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新增分类')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Tree
     */
    protected function tree()
    {
        return Category::tree(function (Tree $tree) {
            $tree->disableCreate();
            $tree->branch(function ($branch) {
                return "{$branch['id']} -- {$branch['title']}";
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Category());

        $form->display('id', 'ID');

        $form->select('parent_id','父分类')->options(Category::selectOptions());

        $form->text('title', '标题')->rules('required');
        $form->text('url', '链接');
        $form->display('created_at', '创建时间');
        $form->display('updated_at', '更新时间');

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });

        $form->disableViewCheck();

        return $form;
    }
}
